package com.study.book.controller;


import cn.hutool.core.io.resource.ClassPathResource;
import com.study.book.common.AuthenticationRequired;
import com.study.book.common.R;
import com.study.book.pojo.Admin;
import com.study.book.res.req.LoginReqVo;
import com.study.book.res.req.UpdateAdminReqVo;
import com.study.book.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Api(tags = "app用户接口")
@RestController
@RequestMapping("/app/user")
public class AppUserController {

    @Autowired
    private AdminService adminService;

    @ApiOperation("app用户登录")
    @PostMapping("/login")
    public R appLogin(@RequestBody LoginReqVo vo) {
        return adminService.appLogin(vo);
    }



    @ApiOperation("图片读取")
    @GetMapping("/images/{imageId}")
    public void showImage(@PathVariable("imageId") String id, HttpServletResponse response) throws IOException {
        ClassPathResource resource = new ClassPathResource("data/images/" + id + ".png");
        BufferedImage image = ImageIO.read(resource.getStream());
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
    }

    @ApiOperation("头像读取")
    @GetMapping("/images/avatar/{imageId}")
    public void showAvatarImage(@PathVariable("imageId") String id, HttpServletResponse response) throws IOException {
        ClassPathResource resource = new ClassPathResource("data/images/avatar/" + id + ".png");
        BufferedImage image = ImageIO.read(resource.getStream());
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
    }

    @ApiOperation("轮播图读取")
    @GetMapping("/images/swipers/{imageId}")
    public void showSwiperImage(@PathVariable("imageId") String id, HttpServletResponse response) throws IOException {
        ClassPathResource resource = new ClassPathResource("data/images/swipers/" + id + ".png");
        BufferedImage image = ImageIO.read(resource.getStream());
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
    }


    @ApiOperation("图片上传")
    @PostMapping(value = "/uploadImages",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R uploadImages(@RequestParam("file") MultipartFile file) throws IOException {

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return R.error("请选择jpg,jpeg,gif,png格式的图片");
        }
        String savePath = "data/images/";
        long fileId = System.currentTimeMillis();
        String filename = fileId + "." + "png";

        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(System.getProperty("user.dir") + "/src/main/resources/" + savePath + filename));
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(System.getProperty("user.dir") + "/target/classes/" + savePath + filename));

        return R.ok(fileId);
    }

    @AuthenticationRequired(value = "0")
    @ApiOperation("用户信息")
    @GetMapping("/userInfo")
    public R<Admin> userInfo(HttpServletRequest request) {
        String id = (String) request.getAttribute("userId");
        return adminService.userInfo(id);
    }

    @AuthenticationRequired(value = "0")
    @ApiOperation("修改当前用户信息")
    @PostMapping("/updateUserInfo")
    public R updateUserInfo(HttpServletRequest request,@RequestBody UpdateAdminReqVo vo) throws IOException {
        String id = (String) request.getAttribute("userId");
        Admin admin = new Admin();
        admin.setAvatar(vo.getAvatar());
        BeanUtils.copyProperties(vo,admin);
        admin.setId(Integer.parseInt(id));
        return adminService.updateUserInfo(admin);
    }

    @ApiOperation("图片上传")
    @PostMapping(value = "/uploadAvatarImages",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R uploadAvatarImages(@RequestParam("file") MultipartFile file) throws IOException {

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return R.error("请选择jpg,jpeg,gif,png格式的图片");
        }
        String savePath = "data/images/avatar/";
        long fileId = System.currentTimeMillis();
        String filename = fileId + "." + "png";

        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(System.getProperty("user.dir") + "/src/main/resources/" + savePath + filename));
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(System.getProperty("user.dir") + "/target/classes/" + savePath + filename));
        return R.ok("avatar/"+fileId);
    }

}
